<template>
  <Page :title="navTitle" @gesture="onGesture">
    <template #navBarCustom>
      <div class="flex items-center navBox">
        <div class="back" @click="back">
          <img class="icon" src="static/icons/back.png" mode="" />
          <span style="color: #fff">{{ navTitle }}</span>
        </div>
        <div class="nav-bar-btns flex" style="margin-left: auto">
          <div class="item flex items-center mr-24px" @click="goToScantron">
            <img class="icon mt-2px mr-4px" src="static/icons/scantron.png" mode="" />
            <span class="name text-white">答题卡</span>
          </div>
          <div class="item flex items-center" @click="submit()">
            <img class="icon mt-2px mr-4px" src="static/icons/scantron-submit.png" mode="" />
            <span class="name text-white">提交</span>
          </div>
        </div>
      </div>
    </template>
    <template #content>
      <div class="w-full h-full p-20px box-border">
        <div
          class="container w-full h-full flex flex-col bg-white p-20px box-border overflow-hidden"
        >
          <div ref="scroll" class="w-full h-full overflow-scroll">
            <!-- 客观题 -->
            <Objective @choose="onChoose"></Objective>
            <!-- 主观题 -->
            <Subjective></Subjective>
          </div>
          <div class="flex justify-center">
            <CustomButton
              class="block mr-84px"
              style="width: 3rem"
              :disabled="questionIndex === 0"
              @click="toPrevQuestion"
              >上一题
            </CustomButton>
            <CustomButton
              ref="next_btn"
              class="block"
              style="width: 3rem"
              v-revert
              @click="toNextQuestion"
              >下一题</CustomButton
            >
          </div>
        </div>
      </div>
    </template>
  </Page>
</template>

<script>
import { mapState } from 'vuex'
// import Page from '@/components/page'
import Page from '@/components/page/newPage'
import Objective from './components/objective/index'
import Subjective from './components/subjective/index'
import CustomButton from '@/components/button/index'
import { creatEexceptionAnalysisApi } from '@/api/common'
import { upExamQuestionAnswerApi } from '@/api/homework'

export default {
  components: {
    Page,
    Objective,
    Subjective,
    CustomButton
  },
  directives: {
    revert: {
      bind: function (el, binding, vnode) {
        el.addEventListener(
          'click',
          () => {
            if (el.OldInnerHTML) {
              el.innerHTML = el.OldInnerHTML
              delete el.OldInnerHTML
            }

            if (el.timerId) {
              clearTimeout(el.timerId)
              delete el.timerId
            }
          },
          false
        )
      }
    }
  },
  beforeRouteLeave(to, from, next) {
    if (to.name === 'homework_scantron' || to.name === 'homework_detail_xkw_index') {
      next()
      return
    }

    if (this.canBack) {
      next()
    } else {
      window.history.pushState(
        null,
        null,
        location.pathname + '#/pages/homework/todo/question/xkw/index'
      )
      this.$popup.show({
        type: 'confirm',
        success: (popup) => {
          popup.$on('cancel', () => {
            this.$popup.hide('confirm')
          })
          popup.$on('confirm', () => {
            this.$popup.hide('confirm')

            this.canBack = true
            this.$router.back()
          })
          popup.setData({
            title: '确认退出？',
            content: '本次进度将保存',
            cancelText: '取消',
            confirmText: '退出'
          })
        }
      })
    }
  },
  data() {
    return {
      canBack: false,
      // 累计时间
      cumulativeTime: {
        vm: this._self,
        timeout: null,
        // 单位：秒
        value: 0,
        // 累加
        run: function () {
          this.timeout = setTimeout(() => {
            const beginTime = this.vm.currentHomework.record.beginTime
            const endTime = this.vm.currentHomework.record.endTime

            if (beginTime && endTime) {
              const endTimestamp = new Date(endTime).getTime()
              const nowTime = new Date().getTime()
              if (nowTime >= endTimestamp) {
                this.vm.submit(true)
                this.vm.$popup.hideAll() // 如果存在弹窗，关闭
                this.vm.$popup.show({
                  type: 'alert',
                  success: (popup) => {
                    popup.$on('confirm', () => {
                      this.vm.$popup.hide('alert')
                    })
                    popup.setData({
                      content: '已超过作答时间，作业已自动提交'
                    })
                  }
                })
                return
              }
            }

            this.value++
            this.run()
          }, 1000)
        },
        reset: function () {
          clearTimeout(this.timeout)
          this.value = 0
        }
      }
    }
  },
  computed: {
    ...mapState(['homework']),
    currentHomework() {
      return this.homework.currentHomework
    },
    questionIndex() {
      const { currentHomework = {} } = this.homework
      const { questionIndex } = currentHomework
      return questionIndex
    },
    questions() {
      const { currentHomework = {} } = this.homework
      const { questions } = currentHomework
      return questions
    },
    currentQuestion() {
      const { currentHomework = {} } = this.homework
      const { questions, questionIndex } = currentHomework
      return questions[questionIndex]
    },
    navTitle() {
      const {
        currentHomework: { questions, questionIndex }
      } = this.homework

      if (questionIndex === -1) return ' '

      const order = questionIndex + 1
      const total = questions.length
      return `第${order}题(${order}/${total})`
    }
  },
  watch: {
    questionIndex: {
      // 监听数据 获取到数据里的数组数据
      handler(newVal, oldVal) {
        this.$refs.scroll.scrollTo(0, 0)

        if (oldVal < 0) return

        // 更新上一题的做题时间
        const { localStudentAnswer } = this.questions[oldVal]
        localStudentAnswer.studentDuration += this.cumulativeTime.value
        this.cumulativeTime.reset()
        this.cumulativeTime.run()
      },
      immediate: false
    },
    currentHomework: {
      handler(newVal, oldVal) {
        const {
          record: { id }
        } = newVal

        this.$storage.homework.putCacheItem({
          id,
          value: newVal
        })
      },
      immediate: false,
      deep: true
    }
  },
  mounted() {
    console.log(this.homework.currentHomework)
    this.cumulativeTime.run()
  },
  beforeDestroy() {
    this.cumulativeTime.reset()
  },
  methods: {
    back() {
      if (this.onBack) {
        this.onBack()
      } else {
        this.$router.go(-1)
      }
    },
    onGesture(direction) {
      switch (direction) {
        case 'right':
          // 上一题
          this.toPrevQuestion()
          break
        case 'left':
          // 下一题
          this.toNextQuestion()
          break
        default:
          break
      }
    },
    onChoose() {
      const {
        next_btn: { $el: el }
      } = this.$refs

      if (el.OldInnerHTML) {
        el.innerHTML = el.OldInnerHTML
        delete el.OldInnerHTML
      }

      if (el.timerId) {
        clearTimeout(el.timerId)
        delete el.timerId
      }

      const oldText = el.innerHTML
      el.OldInnerHTML = oldText

      let count = 3
      const task = (delay) => {
        el.timerId = setTimeout(() => {
          el.innerHTML = count > 0 ? `${oldText}(${count}s)` : oldText
          count -= 1

          if (count < 0) {
            this.toNextQuestion()
          } else {
            task(1000)
          }
        }, delay)
      }

      task(0)
    },
    toPrevQuestion() {
      if (this.questionIndex === 0) return

      this.$store.commit('toPrevQuestion')
    },
    toNextQuestion() {
      if (this.questionIndex === this.questions.length - 1) {
        this.goToScantron()
        return
      }

      this.$store.commit('toNextQuestion')
    },
    goToScantron() {
      const { localStudentAnswer } = this.currentQuestion
      localStudentAnswer.studentDuration += this.cumulativeTime.value
      this.$router.push('/pages/homework/scantron/index')
    },
    submit(force = false) {
      const {
        record: { id },
        questions
      } = this.homework.currentHomework

      const _submit = (questions) => {
        const loading = this.$loading({
          lock: true,
          text: '提交答案...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.5)'
        })
        // 一分钟内上传不成功关闭loading弹窗
        const timer = setTimeout(() => {
          loading.close()
        }, 60000)
        const submitItem = async (questions) => {
          if (questions.length > 0) {
            const { answerScoreable, localStudentAnswer: nextItem } = questions.shift()

            let formdata = nextItem
            if (answerScoreable) {
              const copyNextItem = JSON.parse(JSON.stringify(nextItem))
              copyNextItem.studentAnswer = JSON.stringify(copyNextItem.studentAnswer)
              formdata = copyNextItem
            }

            await upExamQuestionAnswerApi(formdata)
            // 如果单道题做题时间不足10秒，创建异常分析
            if (formdata.studentDuration < 10) {
              const {
                record: { examCode = '', examName, subject, createTime }
              } = this.currentHomework
              // 只上传作业异常分析
              if (!examCode) {
                await creatEexceptionAnalysisApi({
                  type: '1',
                  exceptionDay: this.$utils.parseTime(createTime, '{y}-{m}-{d}'),
                  title: examName,
                  subject
                })
              }
            }
            submitItem(questions)
          } else {
            clearTimeout(timer)
            loading.close()
            this.$message.success('提交成功')
            this.canBack = true
            this.$router.replace('/pages/homework/detail/question/xkw/index')
            this.$nextTick(() => this.$storage.homework.deleteCacheItem(id))
          }
        }

        submitItem(JSON.parse(JSON.stringify(questions)))
      }

      if (force) {
        // 强制提交
        const { localStudentAnswer } = this.currentQuestion
        localStudentAnswer.studentDuration += this.cumulativeTime.value // 更新当前题目的做题时间
        this.cumulativeTime.reset() // 停止计时
        this.$nextTick(() => _submit(questions))
        return
      } else {
        if (Array.isArray(questions)) {
          // 存在未作答的题目
          const unAnswerArr = questions.filter((i) => i.localStudentAnswerStatus === 0)
          const unAnswerCount = unAnswerArr.length

          if (unAnswerCount > 0) {
            this.$popup.show({
              type: 'confirm',
              success: (popup) => {
                popup.$on('cancel', () => {
                  this.$popup.hide('confirm')
                })
                popup.$on('confirm', () => {
                  this.$popup.hide('confirm')
                  const { localStudentAnswer } = this.currentQuestion
                  localStudentAnswer.studentDuration += this.cumulativeTime.value // 更新当前题目的做题时间
                  this.cumulativeTime.reset() // 停止计时
                  this.$nextTick(() => _submit(questions))
                })
                popup.setData({
                  content: '存在未作答的题目，确认提交？'
                })
              }
            })
          } else {
            this.$popup.show({
              type: 'confirm',
              success: (popup) => {
                popup.$on('cancel', () => {
                  this.$popup.hide('confirm')
                })
                popup.$on('confirm', () => {
                  this.$popup.hide('confirm')
                  const { localStudentAnswer } = this.currentQuestion
                  localStudentAnswer.studentDuration += this.cumulativeTime.value // 更新当前题目的做题时间
                  this.cumulativeTime.reset() // 停止计时
                  this.$nextTick(() => _submit(questions))
                })
                popup.setData({
                  content: '确认提交？'
                })
              }
            })
          }
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.navBox {
  padding: 0 20px;
  box-sizing: border-box;
}
.back {
  height: 100%;
  display: flex;
  align-items: center;
  font-size: 28px;

  .icon {
    width: 17.14px;
    height: 30px;
    margin-right: 11px;
  }
}
.nav-bar-btns {
  .item {
    height: 34px;
    .icon {
      width: 34px;
      height: 34px;
    }

    .name {
      font-size: 26px;
      line-height: 26px;
    }
  }
}

.container {
  border-radius: 16px;
}
</style>
